<template>
  <div class="page-container-padding page-view">
    <el-upload
      ref="uploadEle"
      multiple
      accept=".pdf"
      action=""
      :limit="10"
      :auto-upload="false"
      :show-file-list="false"
      :file-list="fileList"
      :before-upload="() => false"
      :on-change="fileSelectChanged"
    >
      <template #tip>
        <div class="uptip">
          仅支持上传PDF文件，单次最多可选择10个文件;若有审核不通过的报告,请修改后再重新上传一篇等待审核即可。
        </div>
      </template>
      <el-button type="primary" icon="el-icon-date" @click="isClearFiles">
        选择周报文件
      </el-button>
    </el-upload>

    <div class="file-list">
      <el-table :key="tableKey" border stripe :data="fileList">
        <el-table-column label="日期" width="180">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.file_date"
              value-format="yyyy-MM-dd"
              type="date"
              :clearable="false"
              @input="rowSelectDateChange"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="文件名"
          show-overflow-tooltip
          min-width="500"
        />
        <el-table-column label="品种" width="200">
          <template #default="scope">
            <el-select
              v-model="scope.row.vcode"
              filterable
              @change="rowVarietyChange(scope.row)"
            >
              <el-option
                v-for="v in fileVarietyList"
                :key="v.variety_en"
                :value="v.variety_en"
                :label="v.variety_name"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <div
              v-if="row.isError"
              class="retry-upload"
              @click="executeUploadRow(row)"
            >
              失败重试
            </div>
            <div v-else>{{ row.statusText }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="percentage" label="进度" width="150">
          <template #default="scope">
            <el-progress
              :text-inside="true"
              :stroke-width="16"
              :percentage="scope.row.percentage"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="mytip">
      {{ uploadTips }}
    </div>

    <div class="actions">
      <el-button
        class="upbtn"
        type="success"
        :loading="uploading"
        @click="startUploadFiles"
      >
        开始上传
      </el-button>
    </div>

    <div class="last-box">
      <el-divider content-position="left">最近的报告</el-divider>
      <el-table :data="lastReports.rows" :row-class-name="tableRowClassName">
        <el-table-column prop="file_date" label="报告日期" width="180" />
        <el-table-column label="名称" show-overflow-tooltip min-width="350">
          <template #default="{ row }">
            <div class="file-title" @click="toShowFile(row)">
              <vab-icon :icon="['fas', 'file-pdf']"></vab-icon>
              {{ row.title }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="variety_name" label="品种" width="150" />
        <el-table-column prop="examine_text" label="组长审核" width="100" />
        <el-table-column
          prop="dept_examine_text"
          label="部门审核"
          width="100"
        />
        <el-table-column prop="create_time" label="创建时间" width="160" />
        <el-table-column label="操作" width="50" align="center">
          <template #default="{ row }">
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="toActionReportRow(row, 1)"
            />
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        hide-on-single-page
        layout="prev, pager, next, jumper"
        style="margin-top: 10px"
        :current-page.sync="lastReports.page"
        :page-size="lastReports.pageSize"
        :total="lastReports.totalCount"
        @current-change="getLastReports"
      />
    </div>
  </div>
</template>
<script>
  import { datetimeToStr } from '@/utils/datetimeUtils'
  import { getRuizyVariety } from '@/api/variety'
  import {
    SliceUpload,
    MergeUpload,
    GetBelongReport,
    DelBelongReport,
  } from '@/api/departmentWork/periodReport'
  export default {
    data() {
      return {
        fileType: 'Weekly',
        tableKey: 0,
        fileVarietyList: [],
        fileList: [],
        uploadTips: '',
        uploading: false,
        resetFileList: false,
        fileVarietyDict: {
          豆类: 'RABMY',
          商品套利: 'RARBIT',
          贵金属: 'RAUAG',
          '棉花(纱)': 'RCFCY',
          棉花: 'RCFCY',
          玉米系: 'RDCCS',
          玉米类: 'RDCCS',
          聚酯: 'REGTA',
          纯碱玻璃: 'RFGSA',
          宏观: 'RHONG',
          股指: 'RIFHC',
          谷物类: 'RJILR',
          菜籽系: 'ROIMS',
          菜籽类: 'ROIMS',
          锰硅硅铁: 'RSMSF',
          硅铁锰硅: 'RSMSF',
          钢材: 'RSTEEL',
          农作物气象: 'RTQTQ',
          焦煤焦炭: 'RZJMJ',
          国债期货: 'RZTGZ',
          沪铝: 'AL',
          铝类: 'RALAO',
          苹果: 'AP',
          沥青: 'BU',
          红枣: 'CJ',
          沪铜: 'CU',
          苯乙烯: 'EB',
          '集运指数(欧线)': 'EC',
          '集运指数（欧线）': 'EC',
          乙二醇: 'EG',
          玻璃: 'FG',
          燃料油: 'FU',
          热卷: 'HC',
          热轧卷板: 'HC',
          铁矿石: 'I',
          焦炭: 'J',
          焦煤: 'JM',
          鸡蛋: 'JD',
          塑料: 'L',
          LLDPE: 'L',
          聚乙烯: 'L',
          碳酸锂: 'LC',
          生猪: 'LH',
          甲醇: 'MA',
          沪镍: 'NI',
          棕榈油: 'P',
          沪铅: 'PB',
          短纤: 'PF',
          花生: 'PK',
          LPG: 'PG',
          液化气: 'PG',
          聚丙烯: 'PP',
          PP: 'PP',
          PX: 'PX',
          对二甲苯: 'PX',
          螺纹钢: 'RB',
          天然橡胶: 'RU',
          合成橡胶: 'BR',
          纯碱: 'SA',
          原油: 'SC',
          硅铁: 'SF',
          烧碱: 'SH',
          锰硅: 'SM',
          工业硅: 'SI',
          沪锡: 'SN',
          纸浆: 'SP',
          不锈钢: 'SS',
          白糖: 'SR',
          PTA: 'TA',
          尿素: 'UR',
          PVC: 'V',
          聚氯乙烯: 'V',
          动力煤: 'ZC',
          郑煤: 'ZC',
          沪锌: 'ZN',
        },
        lastReports: {
          page: 1,
          pageSize: 15,
          totalCount: 0,
          rows: [],
        },
      }
    },
    mounted() {
      // 请求报告品种列表
      getRuizyVariety({ space: 'V01' }).then((res) => {
        this.fileVarietyList = res.data
      })
      this.getLastReports()
    },
    methods: {
      async sliceUploadFile(fileRow) {
        const fileObj = fileRow.raw
        const fileSize = fileObj.size // 文件大小
        const chunkSize = 512 * 1024 // 切片大小512kb
        const chunks = Math.ceil(fileObj.size / chunkSize) // 总块数
        // 将文件切片上传
        for (let i = 0; i < chunks; i++) {
          const start = i * chunkSize
          const end = Math.min(start + chunkSize, fileSize)
          const formData = new FormData()
          formData.append('chunk_index', i) // 块编号
          formData.append('chunk_count', chunks) // 总块数
          formData.append('file_id', fileObj.uid) // 文件ID
          formData.append('chunk_data', fileObj.slice(start, end)) // 块数据
          formData.append('file_name', fileRow.name)
          formData.append('file_date', fileRow.file_date)
          formData.append('file_vcode', fileRow.vcode)
          formData.append('file_type', this.fileType)
          await SliceUpload(formData)
          fileRow.percentage = parseFloat((((i + 1) / chunks) * 100).toFixed(2))
        }
      },

      async startUploadFiles() {
        if (this.resetFileList) {
          this.$baseMessage('这些文件您已经上传过了...', 'error')
          return
        }
        if (this.fileList.length < 1) {
          this.$baseMessage('还没有选择文件...', 'error')
          return
        }
        if (!this.checkBelongVariety()) {
          this.$baseMessage('请先完善报告信息...', 'error')
          return
        }
        this.uploading = true
        this.uploadTips = '正在上传文件列表...'
        for (let i = 0; i < this.fileList.length; i++) {
          const file = this.fileList[i]
          await this.executeUploadRow(file)
        }
        this.uploading = false
        this.resetFileList = true
        this.uploadTips = '上传完成，请检查文件。'
        //
        this.lastReports.page = 1
        this.getLastReports()
      },

      async executeUploadRow(file) {
        file.isError = false
        file.statusText = '正在上传'
        this.tableKey = new Date().getTime()
        try {
          await this.sliceUploadFile(file)
          file.statusText = '正在合并'
          this.tableKey = new Date().getTime()
          const mergeRep = await MergeUpload({
            file_date: file.file_date,
            file_vcode: file.vcode,
            file_name: file.name,
            file_type: this.fileType,
          })
          if (!mergeRep.data.merge) {
            throw new Error('合并文件失败!')
          }
          file.statusText = '上传成功'
          this.tableKey = new Date().getTime()
        } catch (err) {
          file.isError = true
          file.statusText = '上传失败'
          this.tableKey = new Date().getTime()
        }
      },

      checkBelongVariety() {
        this.uploadTips = '正在检测各报告文件所归属的品种...'
        let isPassed = true
        for (let i = 0; i < this.fileList.length; i++) {
          if (!this.fileList[i].vcode) {
            this.uploadTips = '请先完善报告信息再上传!'
            return false
          }
        }
        return isPassed
      },
      isClearFiles() {
        if (this.resetFileList) {
          this.$refs.uploadEle.clearFiles()
          this.fileList = []
          this.resetFileList = false
          this.uploadTips = ''
        }
      },
      fileSelectChanged(file, fileList) {
        this.fileList = fileList.map((f) => {
          f.vcode = f.vcode ? f.vcode : ''
          f.vname = f.vname ? f.vname : ''
          f.isError = f.isError ? f.isError : false
          f.file_date = f.file_date
            ? f.file_date
            : datetimeToStr(new Date(), true, '-')
          f.statusText = f.statusText ? f.statusText : '等待上传'

          if (!f.vcode) {
            for (let fkw in this.fileVarietyDict) {
              if (f.name.indexOf(fkw) > -1) {
                f.vcode = this.fileVarietyDict[fkw]
                break
              }
            }
          }
          return f
        })
      },

      rowVarietyChange(row) {
        if (row.vcode) {
          row.statusText = '准备就绪'
          for (let i = 0; i < this.fileVarietyList.length; i++) {
            if (this.fileVarietyList[i].variety_en === row.vcode) {
              row.vname = this.fileVarietyList[i].variety_name
              break
            }
          }
          this.tableKey = new Date().getTime()
        }
      },
      rowSelectDateChange() {
        this.tableKey = new Date().getTime()
      },

      getLastReports() {
        GetBelongReport(
          this.fileType,
          this.lastReports.page,
          this.lastReports.pageSize
        ).then((res) => {
          this.lastReports.rows = res.data.data
          this.lastReports.page = res.data.page
          this.lastReports.totalCount = res.data.total_count
        })
      },
      toShowFile(row) {
        window.open(row.file_url)
      },
      toActionReportRow(row) {
        this.$baseConfirm(
          '确定删除这篇报告吗?删除后可再我的报告回收站中找回...',
          '提示',
          () => {
            DelBelongReport(row.id, 1).then((res) => {
              this.getLastReports()
            })
          }
        )
      },
      tableRowClassName({ row }) {
        if (row.examine_state === -1 || row.dept_examine_state === -1) {
          return 'examine-reject'
        } else if (row.examine_state === 0 || row.dept_examine_state === 0) {
          return 'examine-stay'
        } else {
          return 'examine-pass'
        }
      },
    },
  }
</script>
<style scoped lang="scss">
  .page-view {
    background-color: #fff;
    .uptip {
      margin-top: 10px;
      color: #174fea;
    }
    .mytip {
      color: #349cfc;
      margin-top: 10px;
    }
    .actions {
      margin: 10px 0;
      .upbtn {
        height: 40px;
        width: 200px;
      }
    }
    .file-list {
      margin-top: 10px;
      .el-date-editor ::v-deep .el-input__inner {
        border: none;
        box-shadow: none;
        border-bottom: 1px solid #5db0fd;
        border-radius: 0;
      }
      .el-select ::v-deep .el-input__inner {
        border: none;
        box-shadow: none;
        border-bottom: 1px solid #5db0fd;
        border-radius: 0;
      }
      .retry-upload {
        cursor: pointer;
        color: #174fea;
      }
    }
    .last-box {
      margin: 25px 0;
      .file-title {
        cursor: pointer;
      }
      .el-table ::v-deep .examine-reject {
        color: #cf3437;
      }
      .el-table ::v-deep .examine-stay {
        color: #444;
      }
      .el-table ::v-deep .examine-pass {
        color: #000;
      }
    }
  }
</style>
